package com.qf.rbac2202.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.rbac2202.sys.entity.SysUser;
import com.qf.rbac2202.sys.service.ISysMenuService;
import com.qf.rbac2202.sys.service.ISysRoleMenuService;
import com.qf.rbac2202.sys.service.ISysUserRoleService;
import com.qf.rbac2202.sys.service.ISysUserService;
import com.qf.rbac2202.utils.Constants;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    ISysUserService userService;


    @Autowired
    ISysMenuService sysMenuService;

    @Autowired
    ISysUserRoleService userRoleService;

    @Autowired
    ISysRoleMenuService roleMenuService;

    /**
     * 获取角色和权限信息
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        final SysUser user = (SysUser) principals.getPrimaryPrincipal();

        final SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        // 查询 user 的权限字符串

        if (user.getUserId().equals(Constants.SUPER_ADMIN_ID)){

            final Set<String> permSet = sysMenuService.queryAdminPermSet();

            simpleAuthorizationInfo.addStringPermissions(permSet);

            return simpleAuthorizationInfo;

        }else {

            final List<String> queryPermList = sysMenuService.queryPermList(user.getUserId());

            simpleAuthorizationInfo.addStringPermissions(queryPermList);

            return simpleAuthorizationInfo;

        }


    }


    /**
     * 获取身份信息
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        final String username = (String) token.getPrincipal();

        // 根据用户名查询用户信息
        final QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);

        final SysUser user = userService.getOne(queryWrapper);

        if (user == null){
            throw new AuthenticationException();
        }

        // 取出密码，返回对象
        final String password = user.getPassword();

        return new SimpleAuthenticationInfo(user, password, ByteSource.Util.bytes(user.getSalt()), this.getName());

    }
}
